package org.cskj.demo.controller;

import org.cskj.demo.pojo.Inshop;
import org.cskj.demo.pojo.Outshop;
import org.cskj.demo.pojo.Shop;
import org.cskj.demo.service.imp.InshopService;
import org.cskj.demo.service.imp.OutshopService;
import org.cskj.demo.service.imp.ShopImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

@Controller
@ResponseBody
@RequestMapping("/outshop")
public class OutshopController {
    private final double size=3;
    @Autowired
    private OutshopService outshopService;
    @Autowired
    private ShopImp shopImp;
    @RequestMapping("/all")
    private List<Outshop> all(int page){
        int count =outshopService.count();
        double pageMax=Math.ceil(count/size);
        System.out.println(count);
        System.out.println(pageMax);
        //计算page是否有效
        page=page>(int)(pageMax)?(int)(pageMax):page;
        //获取数
        List<Outshop> outshops = outshopService.selectAll(page, (int) size);
        return outshops;
    }

    @RequestMapping("/count")
    public int count(){
        int count = outshopService.count();
        return count;
    }

    @RequestMapping("/insert")
    public String insert(Outshop outshop,@RequestParam("uid") String uid){



        Integer u = Integer.valueOf(uid);
        outshop.setOutaddtime(new Date());
        outshop.setUsid(u);


        Integer outid = outshop.getOutid();
        //出库数量
        Integer outnum = outshop.getOutnum();


        Integer shopid = outshop.getShopid();
        //商品库存
        Shop shop = shopImp.selectByKey(shopid);
        Integer shopnum = shop.getShopnum();
        if (outnum>shopnum){
            return "error1";
        }else {
            //可以出库
            outshopService.insert(outshop);
            shop.setShopnum(shopnum-outnum);
            int update = shopImp.update(shop);
            if (update>0){
                return "ok";
            }else {
                return "error";
            }
        }





    }
}
